<template>
  <div class="weekly-page">
    <h2 class="page-title">周报</h2>
    
    <div class="weekly-content">
      <!-- 周报列表 -->
      <transition name="fade" mode="out-in">
        <div v-if="!selectedReport" class="report-list">
          <div v-for="(reports, month) in reportsByMonth" :key="month" class="month-section">
            <h3 class="month-title">{{ month }}</h3>
            <ul class="report-items">
              <li v-for="report in reports" 
                  :key="report.id" 
                  class="report-item" 
                  @click.stop="handleReportClick(report)"
                  @keyup.enter.stop="handleReportClick(report)"
                  tabindex="0"
                  role="button"
                  :aria-label="'查看' + report.title">
                <div class="report-item-header">
                  <span class="report-item-title">{{ report.title }}</span>
                  <span class="report-item-period">{{ report.period }}</span>
                </div>
                <div class="report-item-summary">{{ report.summary }}</div>
              </li>
            </ul>
          </div>
        </div>
      </transition>
      
      <!-- 周报详情 -->
      <transition name="slide" mode="out-in">
        <div v-if="selectedReport" class="report-detail">
          <button class="back-btn" @click.stop="handleBackClick" aria-label="返回周报列表">
            <i class="fas fa-arrow-left"></i>
            <span>返回周报列表</span>
          </button>
          
          <h3 class="detail-title">{{ selectedReport.title }}</h3>
          <p class="detail-period">{{ selectedReport.period }}</p>
          <div class="detail-content markdown-body" v-html="renderedContent"></div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import { marked } from 'marked'
import DOMPurify from 'dompurify'

export default {
  name: 'Weekly',
  data() {
    return {
      weeklyReports: [
        {
          id: 1,
          title: '第一周周报',
          period: '2024-01-01 ~ 2024-01-07',
          summary: '本周主要完成了博客界面的导航栏和首页布局。',
          content: '### 第一周周报\n\n**周期：** 2024-01-01 ~ 2024-01-07\n\n**主要工作：**\n\n1.  完成了博客前端项目的初始化设置。\n2.  设计并实现了响应式导航栏。\n3.  完成了首页的个人信息展示和文章列表布局。\n4.  学习了 Vue.js 的基础知识和组件间通信。\n\n**遇到的问题：**\n\n-   导航栏在不同屏幕尺寸下的适配问题。\n-   组件之间数据传递的理解。\n\n**下周计划：**\n\n-   实现文章详情页。\n-   开始评论功能的开发。\n-   研究 Markdown 渲染和安全过滤。'
        },
        {
          id: 2,
          title: '第二周周报',
          period: '2024-01-08 ~ 2024-01-14',
          summary: '本周主要实现了文章详情页和评论功能的基础。',
          content: '### 第二周周报\n\n**周期：** 2024-01-08 ~ 2024-01-14\n\n**主要工作：**\n\n1.  完成了文章详情页的布局和数据展示。\n2.  实现了评论功能的输入框和评论列表。\n3.  集成了 Markdown 渲染库 `marked`。\n4.  集成了 HTML 过滤库 `DOMPurify` 进行安全处理。\n\n**遇到的问题：**\n\n-   Markdown 渲染结果的样式调整。\n-   评论数据的模拟和管理。\n\n**下周计划：**\n\n-   完善评论功能，支持多级回复。\n-   实现文章发布界面。\n-   开始用户登录功能的初步实现。'
        },
        {
          id: 3,
          title: '第三周周报',
          period: '2024-02-01 ~ 2024-02-07',
          summary: '本周主要完成了用户登录和注册功能。',
          content: '### 第三周周报\n\n**周期：** 2024-02-01 ~ 2024-02-07\n\n**主要工作：**\n\n1.  实现了用户登录和注册功能。\n2.  添加了用户头像和基本信息展示。\n3.  优化了页面交互和用户体验。\n\n**遇到的问题：**\n\n-   用户认证和授权的实现。\n-   表单验证和错误处理。\n\n**下周计划：**\n\n-   实现用户个人中心。\n-   添加文章收藏功能。\n-   优化移动端适配。'
        }
      ],
      selectedReport: null,
      scrollPosition: 0
    }
  },
  computed: {
    renderedContent() {
      if (!this.selectedReport?.content) return ''
      try {
        const rawHtml = marked.parse(this.selectedReport.content)
        return DOMPurify.sanitize(rawHtml)
      } catch (error) {
        console.error('Error rendering markdown:', error)
        return this.selectedReport.content
      }
    },
    reportsByMonth() {
      const grouped = {}
      this.weeklyReports.forEach(report => {
        const date = new Date(report.period.split('~')[0].trim())
        const month = date.toLocaleString('zh-CN', { year: 'numeric', month: 'long' })
        if (!grouped[month]) {
          grouped[month] = []
        }
        grouped[month].push(report)
      })
      // 按月份倒序排序
      return Object.fromEntries(
        Object.entries(grouped).sort((a, b) => {
          const dateA = new Date(a[0].replace('年', '-').replace('月', ''))
          const dateB = new Date(b[0].replace('年', '-').replace('月', ''))
          return dateB - dateA
        })
      )
    }
  },
  methods: {
    handleReportClick(report) {
      console.log('Report clicked:', report) // 添加调试日志
      if (!report) return
      
      // 保存当前滚动位置
      this.scrollPosition = window.scrollY
      
      // 设置选中的报告
      this.selectedReport = { ...report }
      
      // 滚动到顶部
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
      
      // 更新浏览器历史记录
      try {
        history.pushState({ reportId: report.id }, '', `#report-${report.id}`)
      } catch (e) {
        console.error('Failed to update history:', e)
      }
    },
    
    handleBackClick() {
      console.log('Back button clicked') // 添加调试日志
      this.selectedReport = null
      
      // 恢复之前的滚动位置
      setTimeout(() => {
        window.scrollTo({
          top: this.scrollPosition,
          behavior: 'smooth'
        })
      }, 100)
      
      // 更新浏览器历史记录
      try {
        history.pushState(null, '', '#weekly')
      } catch (e) {
        console.error('Failed to update history:', e)
      }
    },
    
    handlePopState(event) {
      console.log('PopState event:', event) // 添加调试日志
      if (event.state && event.state.reportId) {
        const report = this.weeklyReports.find(r => r.id === event.state.reportId)
        if (report) {
          this.handleReportClick(report)
        }
      } else {
        this.handleBackClick()
      }
    }
  },
  created() {
    // 处理浏览器前进后退
    window.addEventListener('popstate', this.handlePopState)
    
    // 检查 URL 中是否有报告 ID
    const hash = window.location.hash
    if (hash && hash.startsWith('#report-')) {
      const reportId = parseInt(hash.replace('#report-', ''))
      const report = this.weeklyReports.find(r => r.id === reportId)
      if (report) {
        this.handleReportClick(report)
      }
    }
  },
  beforeDestroy() {
    window.removeEventListener('popstate', this.handlePopState)
  }
}
</script>

<style scoped>
.weekly-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 2rem;
  margin-bottom: 30px;
  color: var(--dark);
  font-weight: 600;
  text-align: center;
}

.weekly-content {
  max-width: 900px;
  margin: 0 auto;
  background: var(--card-bg);
  border-radius: var(--border-radius-md);
  padding: 30px;
  box-shadow: var(--shadow-md);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.5);
}

.month-section {
  margin-bottom: 40px;
}

.month-section:last-child {
  margin-bottom: 0;
}

.month-title {
  font-size: 1.5rem;
  color: var(--primary);
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid var(--primary-light);
  font-weight: 600;
}

.report-items {
  list-style: none;
  padding: 0;
  margin: 0;
}

.report-item {
  background: var(--light);
  border-radius: var(--border-radius-sm);
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--gray-light);
  cursor: pointer;
  transition: var(--transition);
  user-select: none; /* 防止文本被选中 */
  -webkit-tap-highlight-color: transparent; /* 移除移动端点击高亮 */
}

.report-item:last-child {
  margin-bottom: 0;
}

.report-item:hover {
  transform: translateX(5px);
  box-shadow: var(--shadow-md);
  border-color: var(--primary-light);
  background: white;
}

.report-item:active {
  transform: scale(0.98); /* 添加点击反馈 */
}

.report-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.report-item-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: var(--dark);
}

.report-item-period {
  font-size: 0.9rem;
  color: var(--gray);
  background: var(--gray-light);
  padding: 4px 8px;
  border-radius: 4px;
}

.report-item-summary {
  font-size: 0.95rem;
  color: var(--dark);
  line-height: 1.6;
}

.report-detail {
  background: var(--light);
  border-radius: var(--border-radius-md);
  padding: 40px;
  box-shadow: var(--shadow-lg);
  backdrop-filter: blur(10px);
  border: 1px solid var(--gray-light);
}

.detail-title {
  font-size: 2rem;
  margin-bottom: 15px;
  color: var(--dark);
  font-weight: 600;
}

.detail-period {
  font-size: 1rem;
  color: var(--gray);
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--gray-light);
}

.detail-content {
  line-height: 1.8;
  color: var(--dark);
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 返回按钮 */
.back-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: none;
  background: var(--primary);
  color: white;
  border-radius: 50px;
  cursor: pointer;
  font-size: 0.95rem;
  font-weight: 500;
  transition: var(--transition);
  margin-bottom: 25px;
  box-shadow: var(--shadow-sm);
  outline: none;
}

.back-btn:hover {
  background: var(--primary-dark);
  transform: translateX(-2px);
  box-shadow: var(--shadow-md);
}

.back-btn i {
  font-size: 0.9rem;
}

.back-btn:focus {
  box-shadow: 0 0 0 2px var(--primary-light);
}

.back-btn:focus:not(:focus-visible) {
  box-shadow: var(--shadow-sm);
}

.back-btn:focus-visible {
  box-shadow: 0 0 0 2px var(--primary-light);
}

@media (max-width: 768px) {
  .weekly-page {
    padding: 15px;
  }

  .page-title {
    font-size: 1.8rem;
    margin-bottom: 25px;
  }

  .weekly-content {
    padding: 20px;
  }

  .month-title {
    font-size: 1.3rem;
    margin-bottom: 15px;
  }

  .report-item {
    padding: 15px;
    margin-bottom: 12px;
  }

  .report-item-title {
    font-size: 1rem;
  }

  .report-item-period {
    font-size: 0.85rem;
    padding: 3px 6px;
  }

  .report-item-summary {
    font-size: 0.9rem;
  }

  .report-detail {
    padding: 25px;
  }

  .detail-title {
    font-size: 1.8rem;
  }

  .detail-period {
    font-size: 0.9rem;
    margin-bottom: 20px;
  }

  .back-btn {
    padding: 8px 16px;
    font-size: 0.9rem;
    margin-bottom: 20px;
  }

  .detail-content {
    font-size: 0.95rem;
  }
}

@media (max-width: 480px) {
  .weekly-page {
    padding: 10px;
  }

  .weekly-content {
    padding: 15px;
  }

  .report-item {
    padding: 12px;
  }

  .report-item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .report-item-period {
    align-self: flex-start;
  }

  .report-detail {
    padding: 20px;
  }

  .back-btn {
    width: 100%;
    justify-content: center;
  }
}

/* 添加过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}

.slide-enter,
.slide-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

/* 优化列表项交互 */
.report-item:focus {
  box-shadow: 0 0 0 2px var(--primary-light);
}

.report-item:focus:not(:focus-visible) {
  box-shadow: none;
}

.report-item:focus-visible {
  box-shadow: 0 0 0 2px var(--primary-light);
}
</style> 